import { Injectable } from '@angular/core';
import 'rxjs/add/operator/toPromise';
import {Http, Headers, Response, RequestOptions} from '@angular/http'
import {PersonalMessage} from "../entity/PersonalMessage";
import {PersonalProgectInformation} from "../entity/PersonalProgectInformation";
import {FrontUser} from "../entity/User";
import {Router} from "@angular/router";
import {CommonIp} from "../entity/Ip";
import {FeedBack} from "../entity/FeedBack";
import {Page} from "../../shared/entity/Page";
import {AddressItem} from "../entity/AddressItem";

@Injectable()
export class UserService extends CommonIp{

  private personalMessageURLPrefix=this.userIp+"/p/personal/" ;
  private personalMessageURLSuffix="/personalInformation";
  private personalFollwMessageURLPrefix=this.userIp+"/p/personal/";
  private personalFollwMessageURLSuffix="/followinformation";
  private personalJoinMessageURLPrefix=this.userIp+"/p/personal/";
  private personalJoinMessageURLSuffix="/joininformation";
  private personalSetURLPrefix=this.userIp+"/p/PersonalSet/";
  private personalSetURLSuffix="/GetPersonalSet";
  private persoanlSetUpdateURL=this.userIp+"/p/PersonalSet/UpdatePersonal";
  // private personalLoginURL=this.authServer+"/auth/user/login";
  private personalLoginURL=this.userIp+"/p/User/login";
  private userCountryURL=this.userIp+"/p/PersonalSet/getCountryList";
  public userRankingURL=this.userIp+"/p/User/ranking";
  public insertFeedBackURL=this.userIp+"/p/feedback/InsertFeedBack"

  constructor(public http:Http,public router:Router){
    super();
  }
  public InsertFeedBack(feedback:FeedBack):Promise<void>{

    let headers = new Headers({'Content-Type': 'application/json'});
    let options = new RequestOptions({headers:headers});
    return this.http.post(this.insertFeedBackURL,JSON.stringify(feedback),options)
      .toPromise()
      .then(res => {
        if(res.status<200||res.status>=300){
          throw  new Error('Bad response status:'+res.status);
        }
        if(res.json().code== 404){

          $.jBox.tip("插入数据失败");
        }else if (res.json().code==200){

          $.jBox.tip("提交成功,谢谢您的提交") ;
          this.router.navigate(['/projectindexlist']);
        }
      })

      .catch(this.handleError)

  }
  public getRanking():Promise<FrontUser[]>{
    return this.http.get(this.userRankingURL)
      .toPromise()
      .then(this.extreinfor)
      .catch(this.handleError)
  }

  public getProvince(country:string):Promise<string []>{
    return this.http.get(this.userIp+"/p/PersonalSet/"+country+"/getProvinceList")
      .toPromise()
      .then(this.extreinfor)
      .catch(this.handleError)
  }


  public getCity(province:string):Promise<string[]>{
    return this.http.get(this.userIp+"/p/PersonalSet/"+province+"/getCityList")
      .toPromise()
      .then(this.extreinfor)
      .catch(this.handleError)
  }

  public getArea(city:string):Promise<string[]>{
    return this.http.get(this.userIp+"/p/PersonalSet/"+city+"/getArreaList")
      .toPromise()
      .then(this.extreinfor)
      .catch(this.handleError)
  }
  public getCountry():Promise<string[]>{
    return this.http.get(this.userCountryURL)
      .toPromise()
      .then(this.extreinfor)
      .catch(this.handleError)
  }

  public getPersoanlLogin(user:FrontUser):Promise<void>{

    let headers = new Headers({'Content-Type': 'application/json'});
    let options = new RequestOptions({headers:headers});
    return this.http.post(this.personalLoginURL,JSON.stringify(user),options)
      .toPromise()
      .then(res => {
        if(res.status<200||res.status>=300){
          throw  new Error('Bad response status:'+res.status);

        }


        if(res.json().code == 1011){
          $.jBox.tip("验证码错误，可以点击刷新验证码，重新输入。");
        }

        if(res.json().code== 1008){

          $.jBox.tip("密码错误登陆失败");


        }else if(res.json().code==1012){
          $.jBox.tip("请进行邮箱验证");

        }else if(res.json().code==1013){
          $.jBox.tip("该用户不存在");

        }else if(res.json().code==1014){
          $.jBox.tip("激活链接已经发送到您的邮箱，请激活您的链接");
        }

        else if(res.json().entity!=null&&res.json().entity.email!=null){

          sessionStorage.setItem("email",res.json().entity.email);
          sessionStorage.setItem("name",res.json().entity.name);
          sessionStorage.setItem("id",res.json().entity.id);
          if(res.json().entity.photo!=null){
            sessionStorage.setItem("userimg",this.userimgIp+res.json().entity.photo);
            document.getElementById("ImgHead").setAttribute("src",sessionStorage.getItem("userimg"));

          }

          document.getElementById("loginName").innerHTML = sessionStorage.getItem("name");
          document.getElementById("IsSingOut").innerHTML= "退出";



          this.router.navigate(['app',1]);




          this.router.navigate(['']);
          this.ShowLeftProgram();
        }
      })

      .catch(this.handleError)


  }
  public ShowLeftProgram(){
    document.getElementById("leftCatalog").removeAttribute("style");
    document.getElementById("leftCatalog").setAttribute("style","display:visible");
    document.getElementById("nav").removeAttribute("style");
    document.getElementById("nav").setAttribute("style","display:visible");
    document.getElementById("header").removeAttribute("style");
    document.getElementById("header").setAttribute("style","display:visible");
  }
  public getPersonalMessage(userid:string):Promise<PersonalMessage>{

    return this.http.get(this.personalMessageURLPrefix+userid+this.personalMessageURLSuffix)
      .toPromise()
      .then(this.extreinforEntity)
      .catch(this.handleError)
  }
  public getPersonalFollowMessage(userid:string,pageNo:string):Promise<Page<PersonalProgectInformation>>{

    return this.http.get(this.personalFollwMessageURLPrefix+userid+this.personalFollwMessageURLSuffix+"?pageNo="+pageNo)
      .toPromise()
      .then(this.extractPageInfo)
      .catch(this.handleError)
  }
  private extractPageInfo(res:Response) {
    if(res.status<200||res.status>=300){
      throw  new Error('Bad response status:'+res.status);
    }
    let body = res.json();
    return body.page||{};
  }
  public getPersonalJoinMessage(userid:string,pageNo:string):Promise<Page<PersonalProgectInformation>>{

    return this.http.get(this.personalJoinMessageURLPrefix+userid+this.personalJoinMessageURLSuffix+"?pageNo="+pageNo)
      .toPromise()
      .then(this.extractPageInfo)
      .catch(this.handleError)
  }
  public getPersonalSetMessage(userid:string):Promise<PersonalMessage>{
    return this.http.get(this.personalSetURLPrefix+userid+this.personalSetURLSuffix)
      .toPromise()
      .then(this.extreinforEntity)
      .catch(this.handleError)
  }
  public getPersonalSetUpdateMessage(personalmessage:PersonalMessage):Promise<void>{
    let headers = new Headers({'Content-Type': 'application/json'});
    let options = new RequestOptions({headers:headers});
    return this.http.post(this.persoanlSetUpdateURL,JSON.stringify(personalmessage),options)
      .toPromise()
      .then(res => {
        if(res.status<200||res.status>=300){
          throw  new Error('Bad response status:'+res.status);

        }
        if(res.json().code==200){
          sessionStorage.setItem("userimg",this.userimgIp+personalmessage.photo);
          document.getElementById("ImgHead").setAttribute("src",sessionStorage.getItem("userimg"));
          sessionStorage.setItem("personInfoId",sessionStorage.getItem("id"));
          this.router.navigate(['/personal/',{id:sessionStorage.getItem("personInfoId")}]);

        }
      })
      .catch(this.handleError)
  }

  private extreinfor(res:Response){
    if(res.status<200||res.status>=300){
      throw new Error('Bad response status:'+res.status);
    }
    let body=res.json();

    return body.list||{};
  }
  private  extreinforEntity(res:Response){

    if(res.status<200||res.status>=300){
      throw  new Error('Bad response status:'+res.status);
    }
    let body=res.json();

    return body.entity||{};
  }
  private LoginEntity(res:Response){
    if(res.status<200||res.status>=300){
      throw  new Error('Bad response status:'+res.status);
    }
    if(res.json().entity.email!=null){
      sessionStorage.setItem("email",res.json().entity.email);
      sessionStorage.setItem("name",res.json().entity.name);
      sessionStorage.setItem("id",res.json().entity.id);

      return res.json().entity;
    }
  }
  private handleError(error: any): Promise<any> {
    console.error('An error occurred', error); // for demo purposes only
    return Promise.reject(error.message || error);
  }
  // private headers = new Headers({'Content-Type': 'application/x-www-form-urlencoded'});
}
